﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace ICodeShare.UI.Converters
{
    #region IMultiValueConverter
    /// <summary>
    /// 统计值转换器-多值转换器。对绑定值进行相加求和操作。
    /// </summary>
    /// <example>
    /// 1.在xmal文件引用DateConverter类所在命名空间。
    ///   xmlns:cvts="http://schemas.extended.wpf.com/converters"
    /// 2.在xaml文件添加Resources。
    ///   <Window.Resources>
    ///   <cvts:MultiSumToTotalConverter x:Key="cvtsMultiSumToTotal"/>
    ///   </Window.Resources>
    /// 3.在xaml文件中指定Binding值的Converter，此时需要使用的MultiBinding来指定多组Binding。
    ///  <MultiBinding Converter="{StaticResource cvtsMultiSumToTotal}">
    ///       <Binding Path = "Value" ElementName="slVer"/>   
    ///       <Binding Path = "Value" ElementName="slHor"/>
    ///   </MultiBinding>                
    /// </example>
    [ValueConversion(typeof(double[]), typeof(double))]
    public sealed class MultiSumToTotalConverter : IMultiValueConverter
    {
        #region Members
        /// <summary>
        /// 小数位数
        /// </summary>
        private int _decimals = 2;
        #endregion

        #region Construction
        /// <summary>
        /// 
        /// </summary>
        public MultiSumToTotalConverter()
        {
        }

        /// <summary>
        /// 实例化一个MultiSumToTotalConverter类
        /// </summary>
        /// <param name="decimals">小数位数</param>
        public MultiSumToTotalConverter(int decimals)
        {
            this._decimals = decimals;
        }
        #endregion

        #region Properties

        #region Decimals
        /// <summary>
        /// 返回值中的小数位数
        /// </summary>
        public int Decimals
        {
            get { return this._decimals; }
            set { this._decimals = value; }
        }
        #endregion

        #endregion

        #region  Base Class Overrides 基类方法重写
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            double totalValue = 0.00;
            foreach (object value in values)
            {
                double tranferValue = 0.0;
                if (double.TryParse(value.ToString(), out tranferValue))
                {
                    totalValue += tranferValue;
                }
            }
            totalValue = Math.Round(totalValue, this.Decimals);
            return totalValue;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return null;
        }
        #endregion
    }
    #endregion
}
